package com.example.rbacmanage.controller;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.ChatJoin;
import com.example.rbacmanage.service.ChatJoinService;
import com.example.rbacmanage.vo.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天接入前端控制层
 *
 * @author zmd
 */
@RestController
@RequestMapping("/background/chatJoin")
public class ChatJoinController  {
    @Autowired
    private ChatJoinService chatJoinService;

    /**
     * 分页查询列表
     */
    @PreAuthorize("hasAnyAuthority('background:chatJoin:page')")
    @GetMapping(value = "/page")
    public Result page(ChatJoin entity) {
        return Result.success(chatJoinService.getPage(entity));
    }

    /**
     * 查询列表
     */
    @GetMapping(value = "/list")
    public Result list(ChatJoin entity) {
        return Result.success(chatJoinService.getAll(entity));
    }

    /**
     * 根据id获取详情
     */
    @GetMapping(value = "/{id}")
    public Result getById(@PathVariable(value = "id") Long id) {
        return Result.success(chatJoinService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping(value = "/add")
    public Result save(@RequestBody ChatJoin entity) {
        MyUserDetails myUserDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        entity.setJoinedSystemUserId(myUserDetails.getId().longValue());
        ChatJoin chatJoin = new ChatJoin();
        chatJoin.setMiappUserId(entity.getMiappUserId());
        Integer count = chatJoinService.getCount(chatJoin);
        if (count != null && count > 0){
            return Result.error("当前小程序用户已被其它系统用户接入！");
        }
         chatJoinService.save(entity);
        return Result.success();
    }

    @GetMapping(value = "cancelJoined")
    public Result cancelJoined(ChatJoin entity){
        MyUserDetails myUserDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        entity.setJoinedSystemUserId(myUserDetails.getId().longValue());
        List<ChatJoin> chatJoins = chatJoinService.getAll(entity);
        for (ChatJoin chatJoin:chatJoins){
            chatJoinService.remove(new Long[]{chatJoin.getId()});
        }
        return Result.success();
    }

    /**
     * 更新
     */
    @PutMapping(value = "/update")
    public Result update(@RequestBody ChatJoin entity) {
        chatJoinService.update(entity);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping(value = "/remove")
    public Result deleteByIds(@RequestBody Long[] ids) {
        chatJoinService.remove(ids);
        return Result.success();
    }
}
